package com.wfm.eduservice.service.impl;

import com.wfm.eduservice.entity.EduCourse;
import com.wfm.eduservice.entity.EduCourseDescription;
import com.wfm.eduservice.entity.vo.CoursePublishVo;
import com.wfm.eduservice.entity.vo.CourseInfoVo;
import com.wfm.eduservice.mapper.EduCourseMapper;
import com.wfm.eduservice.service.EduCourseDescriptionService;
import com.wfm.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfm.servicebase.config.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wfm
 * @since 2021-03-10
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    EduCourseDescriptionService description;
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //将CourseInfoVo转换成EduCourse
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        //将CourseInfoVo转换成EduCourseDescription
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        //分别保存
        int insert = baseMapper.insert(eduCourse);
        if(insert==0){
            throw  new GuliException(20001,"添加课程信息失败");
        }
        //获取添加之后课程的id
        String id = eduCourse.getId();
        eduCourseDescription.setId(id);

        description.save(eduCourseDescription);
        return id;
    }

    @Override
    public CourseInfoVo getCourseInfoFormById(String id) {
        EduCourse course = this.getById(id);
        if(course == null){
            throw new GuliException(20001, "数据不存在");
        }
        CourseInfoVo courseInfoForm = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoForm);
        EduCourseDescription courseDescription = description.getById(id);
        if(course != null){
            courseInfoForm.setDescription(courseDescription.getDescription());
        }
        return courseInfoForm;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1 修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if(update == 0) {
            throw new GuliException(20001,"修改课程信息失败");
        }

        //2 修改描述表
        EduCourseDescription d = new EduCourseDescription();
        d.setId(courseInfoVo.getId());
        d.setDescription(courseInfoVo.getDescription());
        description.updateById(d);
    }

    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        return baseMapper.getCoursePublishVoById(id);
    }


}
